/* This DOS utility converts a binary file into an Intel Hex format file. *
 * This is useful for loading files into the ZAX system, since it does not*
 * support binary loads. The load address is zero (fixed).				   *
 *						written by Paul Hutchinson						   */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "dos.h"


FILE	*infile, *outfile;  /* input & output files */

int ch,HiNibble,LoNibble,HiHex,LoHex;

void Nibblet(unsigned char byte)
{

		HiNibble=(byte >> 4) & 15;
		if (HiNibble < 10)
			HiHex = HiNibble+48;
		else
			HiHex = HiNibble+55;
		LoNibble=byte & 15;
		if (LoNibble < 10)
			LoHex = LoNibble+48;
		else
			LoHex = LoNibble+55;

}

void BinToHex(void)
{
	unsigned char	done,l,length,checksum;
	unsigned char	bytes[33];
	unsigned int	address;

	done=0;
	address=0;

	while (!done)
	{
		length=0;
		checksum=0;
		while (length < 32)
		{
			if	((ch = getc(infile)) == EOF)
			{
				done = 1;
				break;
			}
			bytes[++length] = ch;
		}


		Nibblet(length);
		fprintf(outfile,":%c%c",HiHex,LoHex);
		checksum = checksum + 16*HiNibble + LoNibble;

		ch = (address >> 8) & 255;
		Nibblet(ch);
		fprintf(outfile,"%c%c",HiHex,LoHex);
		checksum = checksum + 16*HiNibble + LoNibble;

		ch = address & 255;
		Nibblet(ch);
		fprintf(outfile,"%c%c",HiHex,LoHex);
		checksum = checksum + 16*HiNibble + LoNibble;

		Nibblet(0);
		fprintf(outfile,"%c%c",HiHex,LoHex);
		checksum = checksum + 16*HiNibble + LoNibble;

		address += length;

		for (l=1; l<length+1; l++)
		{
			Nibblet(bytes[l]);
			fprintf(outfile,"%c%c",HiHex,LoHex);
			checksum = checksum + 16*HiNibble + LoNibble;

		}
		ch = 256-checksum;
		Nibblet(ch);
		fprintf(outfile,"%c%c\n",HiHex,LoHex);

	}
	fprintf(outfile,":00000001FF\n");

}

int main(int argc, char *argv[])
{
	if (argc != 3)
	{
		printf("BINTOHEX: convert file\n");
		printf("Usage: BINTOHEX infile outfile\n");
		return EXIT_FAILURE;
	}
	if ((infile = fopen(argv[1], "r")) == NULL)
	{
		fprintf(stderr, "BINTOHEX: Unable to open file: %s\n", argv[1]);
		return EXIT_FAILURE;
	}

	if ((outfile = fopen(argv[2], "w")) == NULL)
	{
		fprintf(stderr, "BINTOHEX: Unable to create file: %s\n", argv[2]);
		return EXIT_FAILURE;
	}

	BinToHex();

	fclose(infile);
	fclose(outfile);

	return EXIT_SUCCESS;
}



